package com.free.rabbitmq.common.template;

import com.free.rabbitmq.common.constant.RabbitConstant;
import com.free.rabbitmq.common.model.MsgLog;
import com.free.rabbitmq.common.model.MsgMail;
import com.free.rabbitmq.common.service.MsgLogService;
import com.free.rabbitmq.common.util.RandomUtil;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

public class MqTemplate {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MsgLogService msgLogService;

    public void sendMail(MsgMail mail) {
        String msgId = RandomUtil.UUID32();
        mail.setMsgId(msgId);
        MsgLog msgLog = new MsgLog(msgId, mail, RabbitConstant.ExchangeQueues.MAIL_EXCHANGE_NAME, RabbitConstant.ExchangeQueues.MAIL_ROUTING_KEY_NAME);
        msgLogService.insertMsg(msgLog);
        CorrelationData correlationData = new CorrelationData(msgId);
        // 发送消息
        this.send(RabbitConstant.ExchangeQueues.MAIL_EXCHANGE_NAME, RabbitConstant.ExchangeQueues.MAIL_ROUTING_KEY_NAME, mail, correlationData);
    }

    public void send(String exchange, String routingKey, Object object, CorrelationData correlationData) {
        rabbitTemplate.convertAndSend(exchange, routingKey, object, correlationData);
    }

}

